package com.evan.uyclub.HomeFragment;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.cardview.widget.CardView;
import androidx.core.content.FileProvider;

import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.evan.uyclub.AppStore.ActivityApp;
import com.evan.uyclub.Other.SetClass;
import com.evan.uyclub.Other.Utlis;
import com.evan.uyclub.R;
import com.evan.uyclub.Rerurn.App_Return;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.squareup.picasso.Picasso;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.DownloadProgressCallBack;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * @noinspection ALL
 */
public class AppFragment extends LazyFragment {
    private static final String KEEP_ER = "3487297072";
    private static final String APP_ID = "488588";
    ObjectAnimator objectAnimator;
    private View view;
    private String apkPath;
    private String api, api2, sin1, sin2, sin3, sin4;
    private App_Return aReturn;
    private ImageView app_vouch, app_game_1, app_funny_1, app_it_1, app_other_1, app_item_icon, app_item_bj;
    private TextView app_item_name, app_item_referral, app_download_url, download_app_text;
    private CardView app_gif_card, download_app;
    private RelativeLayout app_game, app_funny, app_it, app_other;
    private String TOKEN = "";

    /*@Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_app, container, false);
        //初始化应用数据
        initviee();
        *//*Toast.makeText(requireActivity(), "由于应用安全及法律问题应用专区已关闭", Toast.LENGTH_SHORT).show();*//*
        return view;
    }*/

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_app;
    }

    @Override
    protected void initView(View views) {
        view = views;
    }

    @Override
    protected void initData() {
        initAppId();
    }

    @Override
    protected void initEvent() {
        initviee();
    }

    private void initviee() {
        //实现回弹效果，支持带列表的。
        SmartRefreshLayout app_smart = (SmartRefreshLayout) view.findViewById(R.id.app_smart);
        app_smart.setEnableLoadMore(false);
        app_smart.setEnablePureScrollMode(false);
        app_smart.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                initAppId();
                refreshlayout.finishRefresh();
            }
        });
        //设置对应xml界面的字体
        TextView up_title = view.findViewById(R.id.up);
        TextView cloud_title = view.findViewById(R.id.cloud);
        //热门App获取
        app_item_bj = view.findViewById(R.id.app_item_bj);
        app_item_icon = view.findViewById(R.id.app_item_icon);
        app_item_referral = view.findViewById(R.id.app_item_referral);
        app_item_name = view.findViewById(R.id.app_item_name);
        app_download_url = view.findViewById(R.id.item_download_urls);
        app_item_name.setTypeface(Typeface.createFromAsset(requireActivity().getAssets(), "space.ttf"));
        up_title.setTypeface(Typeface.createFromAsset(requireActivity().getAssets(), "english.ttf"));
        cloud_title.setTypeface(Typeface.createFromAsset(requireActivity().getAssets(), "english.ttf"));
        //设置回弹布局效果
        /*app_s=view.findViewById(R.id.app_s);
        app_s.setPureScrollModeOn();*/
        //封面卡片动画
        app_gif_card = view.findViewById(R.id.app_gif_card);
        app_gif_card.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                YoYo.with(Techniques.Tada)
                        .duration(1800)
                        .repeat(0)
                        .playOn(app_gif_card);
            }
        });
        //推荐软件下载
        download_app = view.findViewById(R.id.download_app);
        download_app_text = view.findViewById(R.id.download_app_text);
        download_app_text.setText("下载");
        download_app.setOnClickListener((View view) -> {
            if (download_app_text.getText().toString().equals("下载")) {
                download_app_text.setText("下载ing");
                Download(); // 下载APK
            } else if (download_app_text.getText().toString().equals("安装")) {
                installApk(); // 安装APK
            } else {
                Toast.makeText(requireActivity(), "正在下载中...", Toast.LENGTH_SHORT).show();
            }
        });
        //处理app类跳转
        //和入场动画
        app_game = view.findViewById(R.id.app_game);
        app_funny = view.findViewById(R.id.app_funny);
        app_it = view.findViewById(R.id.app_it);
        app_other = view.findViewById(R.id.app_other);
        app_game.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                objectAnimator = ObjectAnimator.ofFloat(app_game, "alpha", 0f, 1f);
                objectAnimator.setDuration(1000);
                objectAnimator.start();
                Intent intent = new Intent();
                intent.putExtra("title", "Game专区");
                intent.putExtra("token", TOKEN);
                intent.putExtra("lid", aReturn.getSin1());
                intent.putExtra("url", SetClass.getUrl() + "uyapi/lanzou_app_list.php?keeper=" + KEEP_ER + "&api=" + APP_ID + "&id=" + aReturn.getSin1() + "&page=1&accesstoken=" + TOKEN);
                intent.setClass(getActivity(), ActivityApp.class);
                startActivity(intent);
                requireActivity().overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
            }
        });
        app_funny.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                objectAnimator = objectAnimator.ofFloat(app_funny, "alpha", 0f, 1f);
                objectAnimator.setDuration(1000);
                objectAnimator.start();
                Intent intent = new Intent();
                intent.putExtra("title", "好玩系列");
                intent.putExtra("token", TOKEN);
                intent.putExtra("lid", aReturn.getSin2());
                intent.putExtra("url", SetClass.getUrl() + "uyapi/lanzou_app_list.php?keeper=" + KEEP_ER + "&api=" + APP_ID + "&id=" + aReturn.getSin2() + "&page=1&accesstoken=" + TOKEN);
                intent.setClass(getActivity(), ActivityApp.class);
                startActivity(intent);
                requireActivity().overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
            }
        });
        app_it.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                objectAnimator = objectAnimator.ofFloat(app_it, "alpha", 0f, 1f);
                objectAnimator.setDuration(1000);
                objectAnimator.start();
                Intent intent = new Intent();
                intent.putExtra("title", "IT学院");
                intent.putExtra("token", TOKEN);
                intent.putExtra("lid", aReturn.getSin3());
                intent.putExtra("url", SetClass.getUrl() + "uyapi/lanzou_app_list.php?keeper=" + KEEP_ER + "&api=" + APP_ID + "&id=" + aReturn.getSin3() + "&page=1&accesstoken=" + TOKEN);
                intent.setClass(getActivity(), ActivityApp.class);
                startActivity(intent);
                requireActivity().overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
            }
        });
        app_other.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                objectAnimator = objectAnimator.ofFloat(app_other, "alpha", 0f, 1f);
                objectAnimator.setDuration(1000);
                objectAnimator.start();
                Intent intent = new Intent();
                intent.putExtra("title", "Other App");
                intent.putExtra("token", TOKEN);
                intent.putExtra("lid", aReturn.getSin4());
                intent.putExtra("url", SetClass.getUrl() + "uyapi/lanzou_app_list.php?keeper=" + KEEP_ER + "&api=" + APP_ID + "&id=" + aReturn.getSin4() + "&page=1&accesstoken=" + TOKEN);
                intent.setClass(getActivity(), ActivityApp.class);
                startActivity(intent);
                requireActivity().overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
            }
        });

        app_game_1 = view.findViewById(R.id.app_game_1);
        app_funny_1 = view.findViewById(R.id.app_funny_1);
        app_it_1 = view.findViewById(R.id.app_it_1);
        app_other_1 = view.findViewById(R.id.app_other_1);
        app_game_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                YoYo.with(Techniques.Tada)
                        .duration(1200)
                        .repeat(0)
                        .playOn(app_game_1);
            }
        });
        app_funny_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                YoYo.with(Techniques.Tada)
                        .duration(1200)
                        .repeat(0)
                        .playOn(app_funny_1);
            }
        });
        app_it_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                YoYo.with(Techniques.Tada)
                        .duration(1200)
                        .repeat(0)
                        .playOn(app_it_1);
            }
        });
        app_other_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                YoYo.with(Techniques.Tada)
                        .duration(1200)
                        .repeat(0)
                        .playOn(app_other_1);
            }
        });
    }

    private void initAppId() {
        if (!Utlis.isVPNConnected(requireActivity())) {
            EasyHttp.get(SetClass.getNew_url() + "uyapi/file_text.php")
                    .params("keeper", SetClass.getAdmin())
                    .params("api", SetClass.getApi())
                    .params("title", "apps")
                    .execute(new SimpleCallBack<String>() {
                        @Override
                        public void onError(ApiException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onSuccess(String response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                sin1 = jsonObject.getString("sha1");
                                sin2 = jsonObject.getString("sha2");
                                sin3 = jsonObject.getString("sha3");
                                sin4 = jsonObject.getString("sha4");
                                aReturn = new App_Return(sin1, sin2, sin3, sin4);
                                TOKEN = jsonObject.optString("token");
                                //使用Handler将UI更新操作放到主线程中执行
                                new Handler(Looper.getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        app_item_name.setText(jsonObject.optString("name"));
                                        app_item_referral.setText(jsonObject.optString("js"));
                                        app_download_url.setText(jsonObject.optString("url"));
                                        Picasso.with(getActivity()).load(jsonObject.optString("icon")).noPlaceholder().error(R.mipmap.ic_launcher_foreground).into(app_item_icon);
                                        Picasso.with(getActivity()).load(jsonObject.optString("fm")).noPlaceholder().into(app_item_bj);
                                    }
                                });
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
        }
    }


    //下载
    public void Download() {
        String app_url = app_download_url.getText().toString().trim();
        String app_name = app_item_name.getText().toString().trim();
        EasyHttp.downLoad(app_url).saveName(app_name + ".apk")//不设置默认名字是时间戳生成的
                .execute(new DownloadProgressCallBack<String>() {
                    @Override
                    public void update(long bytesRead, long contentLength, boolean done) {
                        int progress = (int) (bytesRead * 100 / contentLength);
                        //download_app_text.setText(progress + "%");
                        if (done) {//下载完成
                            download_app_text.setText("安装");
                        }
                    }

                    @Override
                    public void onStart() {
                        //开始下载
                        download_app_text.setText("下载中");
                    }

                    @Override
                    public void onComplete(String path) {
                        //下载完成，path：下载文件保存的完整路径
                        download_app_text.setText("安装");
                        apkPath = path;
                    }

                    @Override
                    public void onError(ApiException e) {
                        //下载失败
                        download_app_text.setText("失败");
                    }
                });

    }

    /*
     * 下载到本地后执行安装
     */
    private void installApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File apkFile = new File(apkPath);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(getActivity(), getActivity().getPackageName() + ".fileprovider", apkFile);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }
}

